package com.sen.mqtt.hanler;

import com.sen.mqtt.domain.MqttConfigurationProperties;
import com.sen.mqtt.service.TbLampService;
import com.sen.mqtt.service.TbLampStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

/**
 * 接收消息处理器
 * @作者 韩宗森
 * @创建时间 2025年01月22日 17:09
 */
@Component
public class ReceiverMessageHandler implements MessageHandler {

    @Autowired
    private TbLampService tbLampService ;

    @Autowired
    private TbLampStatusService tbLampStatusService ;

    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;

    // 接收到消息就会触发这个方法
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        MessageHeaders headers = message.getHeaders();
        // 获取主题名称
        String receivedTopicName = (String) headers.get("mqtt_receivedTopic");
        if(mqttConfigurationProperties.getSubTopic().equals(receivedTopicName)) {
            // 更新智能灯泡的上线状态
            tbLampService.updateLampOnlineStatus(message.getPayload().toString()) ;
        }else if(mqttConfigurationProperties.getPubTopic().equals(receivedTopicName)) {
            // 服务端获取设备开灯关灯消息
            tbLampStatusService.saveDeviceStatus(message.getPayload().toString()) ;
        }

    }
}
